package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.constants.RegexPatterns;
import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Boolean checkExists(String data, Integer type) {

        //先校验type，只能为1或者2，校验data不能为空，校验data中的数据，当其表达维手机号时，要能匹配手机号的正则
        if (1 != type && 2 != type
                || StringUtils.isBlank(data)
                || (2 == type && !data.matches(RegexPatterns.PHONE_REGEX))) {
            throw new LyException(400, "请求参数格式有误");
        }


        //动态查询统计数据库，如果已经存在返回false,返回true表示不存在
        boolean result = query()
                .eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count() == 1;


        return result;
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String KEY_PREFIX = "ly:user:phone:";

    @Override
    public void sendVerifyCode(String phone) {
//        int arr[] = new int[]{0,1,2,3,4,5,6,7,8,9};
//
//        StringBuffer sb = new StringBuffer();
//        for (int i=0;i<6;i++) {
//            sb.append(arr[(int)(Math.random()*10)]);
//        }
//
//        String cd = sb.toString();


        // 2.使用Apache的工具类生成6位数字验证码
        String code = RandomStringUtils.randomNumeric(6);


        Map<String, String> msg = new HashMap<>();

        msg.put("phone", phone);
        msg.put("code", code);

        //消息发送，发给指定的交换机，同时指定routingKey，消息内容为map
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);

        //把code存入redis等待校验，存5min
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Transactional
    @Override
    public void register(User user, String code) {
        //1,检查验证码,输入的不能为空，输入的验证码必须和redis中的验证码匹配一致
        if (StringUtils.isBlank(code) || !code.equals(redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone()))) {
            throw new LyException(400,"验证码输入有误");
        }

        //使用md5加密，生成密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        save(user);
    }

    @Override
    public UserDTO queryUserByNameAndPass(String username, String password) {

        //根据用户名查询用户
        User user = query().eq("username", username).one();

        //如果用户没有查到即为空，或者密码验证失败，都将到此为止
        if (null==user|| !passwordEncoder.matches(password,user.getPassword())){

            throw new LyException(401,"用户名或密码输入有误");
        }

        return new UserDTO(user);
    }

    @Override
    public void sendMessage() {
        String phone = "18751155078";
        //01随机生成一个验证码
        String code = RandomStringUtils.randomNumeric(6);
        Map<String,String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, map);
        //把code存入redis等待校验，存5min
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

    }
}
